"""
Wordcraft:Chunk\n
/Code/Chunk_Index.py\n
区块操作\n
"""

from Code.ClassDef_Else import Chunk


def XToChunkID(x: int) -> int:
    """
    Wordcraft:Chunk.XToChunkId\n
    根据x坐标获取区块id\n
    参数：\n
    - x: 横坐标\n
    说明：\n
    - 本函数仅作数学运算，不会保证区块真实存在\n
    """

    import math
    if x >= 0:
        # 当x>=0时，所得结果为x/16向下取整×2\n
        return int(math.floor(x/16)*2)
    else:
        # 当x<0时，所得结果是-(x/16)向下取整×2-1\n
        # 使用 x//16 可能会引起混乱， Python 的整数除是向下取整，而 C 等语言则是向0取整\n
        return int(-math.floor(x/16)*2-1)


def ChunkIdToLeftEdge(chunkid: int, LogError: bool = True) -> int:
    """
    Wordcraft:Chunk.ChunkIdToLeftEdge()\n
    根据区块id获取区块左边界\n
    参数：\n
    - chunkid: 区块id\n
    - LogError: 是否输出错误信息\n
    说明：\n
    - 本函数仅作数学运算，不会保证所在区块真实存在\n
    - 务必保证chunkid为非负整数\n
    """
    # 获取全部整数范围内的ID（将非负数还原为最开始的正数或负数）
    if chunkid < 0 or chunkid != int(chunkid):  # 输入不合法
        if LogError:
            import Code.System_Index as System
            with open("gameconfig.json", "r", encoding="utf-8") as f:
                import Code.System_Index as System
                System.Out.Log(System.Out.LangText(
                    "ERROR_CHUNK_CHUNKIDTOLEFTEDFE_IDMUSTNONEGATIVE"),
                    message="ERROR_CHUNK_CHUNKIDTOLEFTEDFE_IDMUSTNONEGATIVE", error_id=chunkid)
        raise ValueError("chunkid must be a non-negative integer")  # 抛出异常
    if chunkid % 2 == 0:  # 偶数 --> 正数\n
        # 当chunkid为偶数时，所得结果为chunkid/2×16\n
        id_belong_Z = chunkid/2
    else:  # 奇数 --> 负数\n
        # 当chunkid为奇数时，所得结果为-(chunkid/2+1)*16\n
        id_belong_Z = -(chunkid+1)/2
    # 将得到的整数范围内的ID×16，得到最终结果
    return int(id_belong_Z*16)


def ChunkIdToFileName(chunkid: int, withdir: bool = False) -> str:
    """
    Wordcraft:Chunk.ChunkIdToFileName\n
    根据区块id获取区块文件名\n
    参数：\n
    - chunkid: 区块id\n
    - withdir: 是否包含目录\n
    说明：\n
    - 本函数仅作字符串运算，不会保证所在区块真实存在\n
    - 务必保证chunkid为非负整数\n
    """
    import json
    result: str  # 结果
    result = "chk"+str(chunkid)+".wc"
    if withdir:
        with open("gameconfig.json", "r", encoding="utf-8") as f:
            conf = eval(f.read().replace(
                "true", "True").replace("false", "False"))
            world_name = conf["world_name"]
            result = "data/"+world_name+"/"+result

    return result


def Create(chunk_id=..., flat: bool = False, seed=...) -> Chunk:
    """
    Wordcraft:Chunk.Create\n
    创建区块\n
    参数：\n
    - chunk_id: 区块id\n
    - flat: 是否为平坦区块\n
    - seed: 随机种子\n
    """
    from Code.ClassDef_Block import Block

    HEIGHT_LIMIT = 256  # 高度限制

    if flat:
        from copy import deepcopy

        # 平坦区块
        result_map = [[Block.builtin("air") for ranger_i in range(
            16)] for range_j in range(HEIGHT_LIMIT)]  # 空区块

        # 填充地形
        result_map[0] = [deepcopy(Block.builtin("bedrock"))
                         for ranger in range(16)]
        result_map[1] = [deepcopy(Block.builtin("stone"))
                         for ranger in range(16)]
        result_map[2] = [deepcopy(Block.builtin("dirt"))
                         for ranger in range(16)]
        result_map[3] = [deepcopy(Block.builtin("grass_block"))
                         for ranger in range(16)]

        # 创建区块对象
        result_chunk = Chunk(result_map, entities=[])
        return result_chunk

    else:
        pass  # 非平坦区块
